/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "spatial_service_timer.h"

#include <thread>

namespace OHOS {
namespace Msdp {
void SpatialServiceTimer::StartTask(int interval, NotifyTask &task)
{
    if (expired_ == false)
        return;

    expired_ = false;
    std::thread([this, interval, task]() {
        while (!tryToExpire_) {
            std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            task();
        }
        {
            std::lock_guard<std::mutex> locker(mutex_);
            expired_ = true;
            expiredCond_.notify_one();
        }
    }).detach();
}

void SpatialServiceTimer::StartTaskOnce(int delay, NotifyTask &task)
{
    std::thread([delay, task]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        task();
    }).detach();
}

void SpatialServiceTimer::StopTask()
{
    if (expired_)
        return;

    if (tryToExpire_)
        return;

    tryToExpire_ = true;
    {
        std::unique_lock<std::mutex> locker(mutex_);
        expiredCond_.wait(locker, [this] {
            return expired_ == true;
        });

        if (expired_ == true)
            tryToExpire_ = false;
    }
}
} // namespace Msdp
} // namespace OHOS